# loading pygame and init
import pygame
from config import config, uiconfig
from translate import l
from ui import initpygame, events, loading, msgbox
from ui.start import startui
from ui.menu import menu
from tools import *
initpygame.init()
exit_flag = False
page = 0
pressmouse = 0
isloaded = False
clock = pygame.time.Clock()
screen = None


def start():
    global page, exit_flag, isloaded, screen
    info("ui/window", "loading...")
    startui.loading_history()
    info("ui/window", "making window")
    mode_type = 0
    if config.config.HW_SURFACE:
        info("ui/window", "[Enable] HWSURFACE")
        mode_type |= pygame.HWSURFACE
    screen = pygame.display.set_mode(config.config.WINDOW_SIZE, mode_type)
    isloaded = True
    from ui import src
    src.main()
    pygame.display.set_caption(config.config.WINDOW_TITLE)
    img = pygame.image.load("src/logo/logo.ico")
    pygame.display.set_icon(img)

    def exit_func():
        global exit_flag
        exit_flag = 1
    while True:
        events.reset()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                if page == 0:
                    exit_flag = True
                    break
                elif page == 2:
                    info("ui/menu", "user cancel progress")
                    exit_flag = True
                    break
                elif page == 1:
                    msgbox.add_msg(l.msg_quit, l.msg_quit_content, exit_func)
            events.update(event)
        if exit_flag:
            break
        screen.fill(uiconfig.BACKGROUND_COLOR)
        if page == 0:
            startui.render_startui(screen)
        elif page == 2:
            loading.render_loading(screen)
        else:
            menu.render_menu(screen)
        msgbox.showmsg(screen)
        clock.tick(120)
        pygame.display.update()
    info("ui/window", "exit")
    pygame.quit()
